package com.meitianhui.convenitenbuy.module.store.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.http.ResponseObserver;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.module.mine.http.MineApiDataSource;
import com.meitianhui.convenitenbuy.module.mine.model.ConsumerAddress;
import com.meitianhui.convenitenbuy.module.mine.ui.activity.ReceivingAddressActivity;
import com.meitianhui.convenitenbuy.module.store.adapter.ShopCarAdapter;
import com.meitianhui.convenitenbuy.module.store.model.ShopCarEvent;
import com.meitianhui.convenitenbuy.module.store.model.ShopCarGoods;
import com.meitianhui.convenitenbuy.util.AddressUtil;
import com.meitianhui.convenitenbuy.util.PreferenceUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.StringUtils;
import com.meitianhui.convenitenbuy.util.SystemUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.meitianhui.convenitenbuy.R.id.tv_favourable_price;

/**
 * Created by Administrator on 2017/11/24.
 */

public class ShopCarActivity extends BaseToolbarActivity {
    private RelativeLayout mRlAddress;
    private RecyclerView mRvGood;
    private TextView mTvTotalPrice, mTvFavourablePrice;        //合计 优惠
    private TextView mTvPrice, mTvNumber;
    private TextView mTvStoreName;
    private TextView mTvName, mTvPhone, mTvAddress;
    private EditText mEtFeedBack;
    private CheckBox mCbCheck;
    private int mNumber = 0;       //总数量
    private BigDecimal mTotalPrice; //总金额
    private BigDecimal mFavourablePrice = new BigDecimal("0"); //总返利金额
    private String mStoreId;
    private String mStoreName;
    private String mStoreAddress;
    private List<ShopCarGoods> mShopCarGoodsList;
    private ShopCarAdapter mAdapter;
    private List<ConsumerAddress.ConsumerData> consumerDataList;
    private boolean mPaySuccess  = false;

    @Override
    protected int setView() {
        return R.layout.activity_shop_car;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        initView();
        initData();
    }


    private void initView() {
        setTbTitle("购物车");
        isEnable(false);
        mEtFeedBack = getViewById(R.id.et_feed_back);
        mTvTotalPrice = getViewById(R.id.tv_total_price);
        mTvFavourablePrice = getViewById(tv_favourable_price);
        mTvPrice = getViewById(R.id.tv_price);
        mTvNumber = getViewById(R.id.tv_number);
        mTvStoreName = getViewById(R.id.tv_store_name);
        mRlAddress = getViewById(R.id.rl_address);
        RxUtils.bindEvents(mRlAddress, this);
        RxUtils.bindEvents(getViewById(R.id.tv_pay), this);
        mTvName = getViewById(R.id.tv_name);
        mTvPhone = getViewById(R.id.tv_phone);
        mTvAddress = getViewById(R.id.tv_address);
        mCbCheck = getViewById(R.id.cb_check);
        RxUtils.bindEvents(mCbCheck, this);
        mRvGood = getViewById(R.id.rv_good);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRvGood.setLayoutManager(layoutManager);
        registerPush();

    }

    private void registerPush() {
        Disposable subscribe = RxBus.get().toFlowable(EventBean.class).subscribe(new Consumer<EventBean>() {
            @Override
            public void accept(EventBean eventBean) throws Exception {
                if (eventBean.getType() == Constants.EVENT_TYPE_REFRESH) {
                    finish();
                    mPaySuccess = true;
                }
            }
        });
        mCompositeDisposable.add(subscribe);
    }

    private void initData() {

        Intent intent = this.getIntent();
        mStoreId = intent.getStringExtra("store_id");
        mStoreName = intent.getStringExtra("store_name");
        mStoreAddress = intent.getStringExtra("store_address");
        mShopCarGoodsList = (List<ShopCarGoods>) intent.getSerializableExtra("good_list");
        mTvStoreName.setText(mStoreName);
        mAdapter = new ShopCarAdapter(mShopCarGoodsList);
        mRvGood.setAdapter(mAdapter);
        setIsAllCheck();
        setGoodInfo();
        mAdapter.setOnClickListener(new ShopCarAdapter.ShopCarAdapterOnClickListener() {
            @Override
            public void add(int position) {
                ShopCarGoods shop = mShopCarGoodsList.get(position);
                int add = (Integer.parseInt(shop.getNum()) + 1);
                if (Integer.parseInt(shop.getStock_qty()) < add) {
                    TipUtils.showToast(App.getInstance(), "库存不足！");
                } else {
                    mShopCarGoodsList.get(position).setNum(add + "");
                    mAdapter.notifyDataSetChanged();
                }
                setGoodInfo();
            }

            @Override
            public void delete(int position) {
                ShopCarGoods shop = mShopCarGoodsList.get(position);
                String num = shop.getNum();
                if (num.equals("1")) {
                    mShopCarGoodsList.remove(position);
                    mAdapter.notifyDataSetChanged();
                } else {
                    mShopCarGoodsList.get(position).setNum((Integer.parseInt(shop.getNum()) - 1) + "");
                    mAdapter.notifyDataSetChanged();
                }
                setGoodInfo();
            }

            @Override
            public void isCheck(int position, boolean check) {
                if (!check) {
                    mShopCarGoodsList.get(position).setIschecek(true);
                    setIsAllCheck();
                } else {
                    mShopCarGoodsList.get(position).setIschecek(false);
                    mCbCheck.setChecked(false);
                }
                mAdapter.notifyDataSetChanged();
                setGoodInfo();
            }
        });
    }

    /**
     * 判断是否全部选中
     */
    private void setIsAllCheck(){
        boolean allCheck = true;
        for (int i = 0; i < mShopCarGoodsList.size(); i++) {
            boolean isCheck = mShopCarGoodsList.get(i).ischecek();
            if (!isCheck) {
                allCheck = false;
                break;
            }
        }
        if (allCheck) {
            mCbCheck.setChecked(true);
        } else {
            mCbCheck.setChecked(false);
        }
    }

    private void setGoodInfo() {
        mNumber = 0;
        mTotalPrice = new BigDecimal("0");
        mFavourablePrice = new BigDecimal("0");
        int checkNum = mShopCarGoodsList.size();
        for (int i = 0; i < checkNum; i++) {
            if (mShopCarGoodsList.get(i).ischecek()) {
                mNumber += Integer.parseInt(mShopCarGoodsList.get(i).getNum());
                String money = StringUtils.moneyMul(mShopCarGoodsList.get(i).getPrice(), mShopCarGoodsList.get(i).getNum());
                BigDecimal value = new BigDecimal(money);
                mTotalPrice = StringUtils.moneyAdd(mTotalPrice, value);
                if (!TextUtils.isEmpty(mShopCarGoodsList.get(i).getRebate())) {
                    String money_return = StringUtils.moneyMul(mShopCarGoodsList.get(i).getRebate(), mShopCarGoodsList.get(i).getNum());
                    BigDecimal value_return = new BigDecimal(money_return);
                    mFavourablePrice = StringUtils.moneyAdd(mFavourablePrice, value_return);
                }
            }
        }
        mTvNumber.setText(mNumber + "");//总数量
        mTvNumber.setTag(mNumber + "");
        mTvTotalPrice.setText("¥" + mTotalPrice.toString());
        mTvTotalPrice.setTag(mTotalPrice.toString());
        mTvFavourablePrice.setText("¥0.00");
        mTvFavourablePrice.setTag("0.00");
        mTvPrice.setText("¥" + mTotalPrice.toString());
        mTvPrice.setTag(mTotalPrice.toString());
    }


    @Override
    protected void onResume() {
        super.onResume();
        List<ConsumerAddress.ConsumerData> consumerDataListCache = InfoProvider.getUserReceivingAddress(this);
        if (consumerDataListCache != null) {
            if (consumerDataListCache.size() > 0) {
                for (int i= 0;i<consumerDataListCache.size();i++){
                    if(TextUtils.equals(consumerDataListCache.get(i).getIs_major_addr(),"Y")){
                        mTvName.setText(consumerDataListCache.get(i).getConsignee());
                        mTvPhone.setText(consumerDataListCache.get(i).getMobile());
                        String area = AddressUtil.getSSQ(this, consumerDataListCache.get(i).getArea_id());
                        String address = consumerDataListCache.get(i).getAddress();
                        mTvAddress.setText(area + address);
                    }
                }
            } else {
                mTvName.setText("");
                mTvPhone.setText("");
                mTvAddress.setText("");
            }
        }else {
            //从服务器拉取数据,暂时不写presenter
            Map<String, String> map = new HashMap<>();
            map.put("consumer_id", InfoProvider.getUserToken(this).getMember_id());
            MineApiDataSource.getInstance().getUserReceivingAddress(InfoProvider.getAppToken(this), "member.consumerAddressFind", new Gson().toJson(map)).subscribe(new ResponseObserver<ConsumerAddress>(this) {
                @Override
                public void onSuccess(ConsumerAddress data) {
                    List<ConsumerAddress.ConsumerData> consumerData= data.data;
                    if (consumerData.size() > 0) {
                        for (int i= 0;i<consumerData.size();i++){
                            if(TextUtils.equals(consumerData.get(i).getIs_major_addr(),"Y")){
                                mTvName.setText(consumerData.get(i).getConsignee());
                                mTvPhone.setText(consumerData.get(i).getMobile());
                                String area = AddressUtil.getSSQ(ShopCarActivity.this, consumerData.get(i).getArea_id());
                                String address = consumerData.get(i).getAddress();
                                mTvAddress.setText(area + address);
                            }
                        }
                        //保存到本地
                        PreferenceUtils.saveObject(ShopCarActivity.this, Constants.USER_RECEIVING_ADDRESS,consumerData);
                    } else {
                        mTvName.setText("");
                        mTvPhone.setText("");
                        mTvAddress.setText("");
                    }

                }
            });
        }

    }

    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {
            case R.id.rl_address:   //地址

                Intent intentAdd = new Intent(ShopCarActivity.this, ReceivingAddressActivity.class);
                startActivity(intentAdd);

                break;

            case R.id.cb_check:  //全选
                if (!mCbCheck.isChecked()) { //不选中
                    mCbCheck.setChecked(false);
                    for (int i = 0; i < mShopCarGoodsList.size(); i++) {
                        mShopCarGoodsList.get(i).setIschecek(false);
                    }
                } else { //选中
                    mCbCheck.setChecked(true);
                    for (int i = 0; i < mShopCarGoodsList.size(); i++) {
                        mShopCarGoodsList.get(i).setIschecek(true);
                    }
                }
                mAdapter.notifyDataSetChanged();
                setGoodInfo();
                break;

            case R.id.tv_pay:  //支付
                SystemUtils.hidKeyBoard(ShopCarActivity.this);
                Integer num = Integer.parseInt(mTvNumber.getText().toString());
                if (num <= 0) {
                    TipUtils.showToast(App.getInstance(), "请选择商品购买", 3);
                    return;
                }
                if (TextUtils.isEmpty(mTvName.getText().toString())) {
                    Toast.makeText(App.getInstance(), "请添加收货地址", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(ShopCarActivity.this, ShopCarPayActivity.class);
                intent.putExtra("store_name", mStoreName);
                intent.putExtra("store_address", mStoreAddress);
                intent.putExtra("store_id", mStoreId);
                intent.putExtra("list", (Serializable) mShopCarGoodsList);
                intent.putExtra("pay_price", mTvPrice.getTag().toString());//优惠后的价格(应付)
                intent.putExtra("discount_price", mTvFavourablePrice.getTag().toString());//已优惠的价格
                intent.putExtra("total_price", mTvTotalPrice.getTag().toString() + "");//总额
                intent.putExtra("number", mTvNumber.getTag().toString());//总数
                intent.putExtra("receive_name", mTvName.getText().toString());//收货人名称
                intent.putExtra("receive_phone", mTvPhone.getText().toString());//收货人电话
                intent.putExtra("receive_address", mTvAddress.getText().toString());//收货人地址
                intent.putExtra("all_value_return", mFavourablePrice.toString());
                intent.putExtra("feed_back", mEtFeedBack.getText().toString());//意见
                startActivity(intent);
                break;


        }
    }

    @Override
    protected void onRefreshData() {

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mPaySuccess){
            int number = 0;
            for (int i = mShopCarGoodsList.size() - 1; i >= 0; i--) {
                if(!mShopCarGoodsList.get(i).ischecek()){
                    number += Integer.valueOf(mShopCarGoodsList.get(i).getNum());
                }
                if (mShopCarGoodsList.get(i).ischecek()) {
                    mShopCarGoodsList.remove(i);
                }
            }
            RxBus.get().post(new ShopCarEvent(Constants.EVENT_TYPE_CAR_RETURN, number, mShopCarGoodsList));
        }else{
            RxBus.get().post(new ShopCarEvent(Constants.EVENT_TYPE_CAR_RETURN,mNumber, mShopCarGoodsList));
        }

    }

}
